<template>
  <div>
    <el-dialog
      destroy-on-close
      :title="title"
      :visible.sync="visible"
      :close-on-click-modal="false"
      fullscreen
      @close="onClose"
      @open="onOpen"
    >
      <el-card class="head-card">
        <el-form class="searchForm" :inline="true" :model="queryForm" label-width="150px">
          <el-form-item label="所属部门">
            <el-select v-model="queryForm.modelcode" prop="modelcode" placeholder="全部">
              <el-option label="全部" value="all"></el-option>
              <el-option
                v-for="(item, index) in modelcodedata"
                :key="`modelcodedata1-${index}`"
                :label="item.orgname"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审批通过后执行过程">
            <el-input v-model="queryForm.finalexecpro" prop="finalexecpro" />
          </el-form-item>

          <el-form-item>
            <el-button type="info" @click="onSearch">查询</el-button>
            <el-button type="info" :disabled="visibleAdd == '1'" @click="Add">添加</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <div class="block">
        <el-timeline>
          <el-timeline-item v-for="(item, index) in tableData" :key="`tableData-${index}`" placement="top">
            <el-card>
              <el-form
                :ref="`tableData${index}`"
                :rules="rules"
                :inline="true"
                :model="item"
                class="demo-form-inline"
                label-width="150px"
                label-position="right"
              >
                <el-row>
                  <el-col :span="24">
                    <el-form-item class="del">
                      <el-button type="danger" @click="onDel(item, index)">删除</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="审批级次" prop="checklevel">
                      <el-input v-model.number="item.checklevel" placeholder="审批级次"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="是否为多人审批">
                      <el-select v-model="item.ismorepep" placeholder="否">
                        <el-option label="是" :value="1"></el-option>
                        <el-option label="否" :value="0"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="部门">
                      <el-input
                        v-model="item.checkorgname"
                        placeholder="部门"
                        clearable
                        @change="queryKey()"
                        @clear="queryKey(index)"
                      >
                        <el-button
                          slot="append"
                          type="info"
                          icon="el-icon-zoom-in"
                          @click="onOpenBm(index)"
                        ></el-button>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="通过后抄送他人">
                      <el-input
                        v-model="item.ccusername"
                        placeholder="通过后抄送他人"
                        clearable
                        @change="queryCcusername('cstr')"
                        @clear="queryCcusername('cstr')"
                      >
                        <el-button
                          slot="append"
                          type="info"
                          icon="el-icon-zoom-in"
                          @click="onOpenRy(index, 'cstr')"
                        ></el-button>
                      </el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="级次描述" prop="checkdis">
                      <el-select v-model="item.checkdis" placeholder="请选择">
                        <el-option
                          v-for="(item, index) in checkdisdata"
                          :key="`chekcid-${index}`"
                          :label="item.valueinfo"
                          :value="item.valueinfo"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="是否需要所有人同意">
                      <!-- 区别别的字段都是"0" 次字段是0 所以没有加：" -->
                      <el-select v-model="item.isallpepagree" placeholder="否">
                        <el-option label="是" value="1"></el-option>
                        <el-option label="否" value="0"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="审批人">
                      <el-input
                        v-model="item.checkusername"
                        placeholder="审批人"
                        clearable
                        @change="queryCcusername('spr')"
                        @clear="queryCcusername('spr')"
                      >
                        <el-button
                          slot="append"
                          type="info"
                          icon="el-icon-zoom-in"
                          @click="onOpenRy(index, 'spr')"
                        ></el-button>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="一票终审权">
                      <el-input
                        v-model="item.finalusername"
                        placeholder="一票终审权"
                        clearable
                        @change="queryCcusername('ypzs')"
                        @clear="queryCcusername('ypzs')"
                      >
                        <el-button
                          slot="append"
                          type="info"
                          icon="el-icon-zoom-in"
                          @click="onOpenRy(index, 'ypzs')"
                        ></el-button>
                      </el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="退回级次" prop="returnlevel">
                      <el-input v-model="item.returnlevel" placeholder="退回级次"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="是否有终审权" prop="isfinal">
                      <el-select v-model="item.isfinal" placeholder="否" @change="isfinal(item.isfinal)">
                        <el-option label="是" :value="1"></el-option>
                        <el-option label="否" :value="0"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="岗位">
                      <el-input
                        v-model="item.checkpostname"
                        placeholder="岗位"
                        clearable
                        @change="queryCheckpostname()"
                        @clear="queryCheckpostname()"
                      >
                        <el-button
                          slot="append"
                          type="info"
                          icon="el-icon-zoom-in"
                          @click="onOpenGw(index)"
                        ></el-button>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="时效工作日" prop="effdatenum">
                      <el-input v-model.number="item.effdatenum" placeholder="时效工作日"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="24" :md="16" :lg="12">
                    <el-form-item class="examurl" label="待办进入地址" prop="examurl" style="width: 100%">
                      <el-input v-model="item.examurl" style="width: 100%" placeholder="待办进入地址"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="通过后调过程">
                      <el-input v-model="item.execporc" placeholder="通过后调过程"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="12" :md="8" :lg="6">
                    <el-form-item label="下审批级次" prop="nextlevel">
                      <el-input v-model.number="item.nextlevel" placeholder="下审批级次">
                        <el-button
                          slot="append"
                          type="info"
                          icon="el-icon-zoom-in"
                          @click="onOpenXjsp(item)"
                        ></el-button>
                      </el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
      <el-card class="foot-card">
        <el-form :inline="true" :model="formInline" class="foot-form">
          <el-form-item>
            <el-button type="info" @click="onCopy">流程复制</el-button>
          </el-form-item>
          <el-form-item label="部门">
            <el-select v-model="formInline.region" placeholder="全部">
              <el-option label="全部" value="all"></el-option>
              <el-option
                v-for="(item, index) in modelcodedata"
                :key="`modelcodedata2-${index}`"
                :label="item.orgname"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="info" @click="onSubmit">保存</el-button>
            <el-button type="info" @click="onClose">关闭</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-dialog>
    <bumen :visiblesbm="visiblesbm" @fatherbm="visiblesbm = false" @onChoosebm="onChoosebm"></bumen>
    <gangwei :visiblesgw="visiblesgw" @fathergw="visiblesgw = false" @onChoosegw="onChoosegw"></gangwei>
    <renyuan :visiblesry="visiblesry" @fatherry="visiblesry = false" @onChoosery="onChoosery"></renyuan>
    <xiashenpijici
      :visiblesxspjc="visiblesxspjc"
      :row-data="RowData"
      @fatherxspjc="visiblesxspjc = false"
    ></xiashenpijici>
  </div>
</template>

<script>
import bumen from './components/bumen.vue'
import gangwei from './components/gangwei.vue'
import renyuan from './components/renyuan.vue'
import xiashenpijici from './components/xiashenpijici.vue'

import { ReCheckOrgList, ExamDeptLevel, DelLevel, SaveDeptLevel, CopyDeptExam } from '@/api/settings/shenpimoban'
import { QueryPageList } from '@/api/settings/zidian'

export default {
  name: 'Processdialog',
  components: { bumen, gangwei, renyuan, xiashenpijici },
  props: ['visiblesSP', 'datarow'],

  data() {
    return {
      modelid: this.datarow.id,
      // 控制弹框显示
      visible: this.visiblesSP,
      // 标题名称
      title: '流程配置',
      // 查询数据
      queryForm: {
        modelcode: 'all',
        finalexecpro: ''
      },
      // 数据
      tableData: [],
      // 底部部门
      formInline: {
        region: 'all'
      },
      // 部门下拉数据
      modelcodedata: [],
      // 级次描述下拉
      checkdisdata: [],
      // 控制添加按钮只读
      visibleAdd: '0',
      // 部门显示与隐藏
      visiblesbm: false,
      // 岗位显示与隐藏
      visiblesgw: false,
      // 人员显示与隐藏
      visiblesry: false,
      // 下审批级次显示与隐藏
      visiblesxspjc: false,
      // 点击按钮数据
      DataIndex: '',
      Namery: '',
      // 下审批级次数据
      RowData: [],

      rules: {
        checklevel: [
          { required: true, message: '请输入审批级次', trigger: 'blur' },
          { type: 'number', message: '审批级次必须为数字值' }
        ],
        checkdis: [{ required: true, message: '请输入级次描述', trigger: 'blur' }],
        returnlevel: [{ required: true, message: '请输入退回级次', trigger: 'blur' }],
        isfinal: [{ required: true, message: '请选择是否有终审权', trigger: 'change' }],
        effdatenum: [
          { required: true, message: '请输入时效工作日', trigger: 'blur' },
          { type: 'number', message: '时效工作日必须为数字值' }
        ],
        examurl: [{ required: true, message: '请输入待办进入地址', trigger: 'blur' }],
        nextlevel: [
          { required: true, message: '请输入下审批级次', trigger: 'blur' },
          { type: 'number', message: '时效工作日必须为数字值' }
        ]
      }
    }
  },
  // 这里用watch方法来监听父组件传过来的值，来实现实时更新
  watch: {
    visiblesSP(val) {
      // message即为父组件的值，val参数为值
      this.visible = val // 将父组件的值赋给childrenMessage 子组件的值
    },
    datarow(val) {
      // message即为父组件的值，val参数为值
      this.modelid = val.id // 将父组件的值赋给childrenMessage 子组件的值
    }
  },
  created() {
    // this.onOpen()
  },
  methods: {
    // 部门下拉
    async modelcode() {
      this.modelcodedata = []
      const { content } = await ReCheckOrgList()
      console.log(content)
      content.forEach(item => {
        console.log(item)
        this.modelcodedata.push({ id: item.id, orgname: item.orgname })
      })
    },
    async checkdi() {
      this.checkdisdata = []
      const { content } = await QueryPageList({ groupinfo: 'ExamLevelTitle' })
      this.checkdisdata = content.list
      console.log(this.checkdisdata)
    },
    // 查询数据
    async onSearch() {
      this.checkdi()
      // this.modelcode()

      this.loading = true
      this.visibleAdd = '0'

      const data = { modelid: this.modelid, dpid: this.queryForm.modelcode }
      const { content } = await ExamDeptLevel(data)
      console.log(content)
      console.log(content.detail == null)
      if (content.detail == null) {
        content.detail = []
      }
      content.detail.forEach(item => {
        if (item.isfinal == '1') {
          this.visibleAdd = '1'
        }
        if (item.ismorepep == null || item.ismorepep == '') {
          item.ismorepep = 0
        }
        if (item.isallpepagree == null || item.isallpepagree == '') {
          item.isallpepagree = 0
        }
      })
      this.queryForm.finalexecpro = content.finalexecpro

      this.tableData = content.detail
      console.log()
      alert('数据加载完成')
      this.loading = false
    },
    // 弹框打开
    onOpen() {
      this.checkdi()
      this.modelcode()
      this.onSearch()
    },
    // 添加
    Add() {
      this.tableData.push({
        ismorepep: 0,
        isallpepagree: '0',
        isfinal: 0
      })
    },
    // 删除
    onDel(row, indexs) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          if (row.id) {
            await DelLevel({ levelid: row.id })
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.onSearch()
          } else {
            this.tableData = this.tableData.filter((item, index) => {
              return index != indexs
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })

      console.log(row, indexs)
    },
    // 是否有终审权变化
    isfinal(row) {
      console.log(row)
      this.visibleAdd = row
    },
    // 部门选择
    onOpenBm(row) {
      console.log(row)
      this.DataIndex = row
      this.visiblesbm = true
    },
    // 人员选择
    onOpenRy(row, name) {
      this.DataIndex = row
      this.Namery = name
      this.visiblesry = true
    },
    // 岗位
    onOpenGw(row) {
      this.DataIndex = row
      this.visiblesgw = true
    },
    // 下级审批
    onOpenXjsp(row) {
      if (!row.id) {
        alert('请先保存在进行添加')
        return
      } else {
        this.visiblesxspjc = true
        this.RowData = row
      }
    },
    // 复制流程
    async onCopy() {
      // if (this.queryForm.modelcode == undefined) {
      //   this.queryForm.modelcode = 'all'
      // }
      // if (this.formInline.region == undefined) {
      //   this.formInline.region = 'all'
      // }
      let modelcode = ''
      let region = ''
      this.modelcodedata.forEach(item => {
        if (this.queryForm.modelcode == item.id) {
          modelcode = item.orgname
        }
        if (this.formInline.region == item.id) {
          region = item.orgname
        }
      })
      if (modelcode == '') {
        modelcode = '全部'
      }
      if (region == '') {
        modelcode = '全部'
      }
      console.log(modelcode, this.queryForm.modelcode)
      console.log(region, this.formInline.region)

      if (this.queryForm.modelcode == this.formInline.region) {
        alert('源部门与目标部门不能相同')
        return
      }

      this.$confirm('确定将' + modelcode + '部门的审批链复制到' + region + '部门？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await CopyDeptExam({
            modelid: this.modelid,
            sourcedpid: this.queryForm.modelcode,
            targetdpid: this.formInline.region
          })
          console.log(res)
          this.$message({
            type: 'success',
            message: res.message
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消复制'
          })
        })
    },
    // 保存
    validateRow(index) {
      return new Promise(resolve => {
        this.$refs[`tableData${index}`][0].validate(valid => resolve(valid))
      })
    },
    async onSubmit() {
      // return new Promise(resolve => {
      // this.$refs[`tableData${index}`][0].validate(valid => resolve(valid))
      // })
      let tdindex = 0
      for (let index = 0; index < this.tableData.length; index++) {
        // const item = this.tableData[index]
        const res = await this.validateRow(index)
        if (!res) {
          tdindex++
          continue
        }
      }
      if (tdindex == 0) {
        // // 审批模板id
        // this.modelid
        // // 部门id
        if (this.queryForm.modelcode == undefined || this.queryForm.modelcode == '') {
          this.queryForm.modelcode = 'all'
        }
        // // 审批通过后执行的存储过程名称
        if (this.queryForm.finalexecpro == null) {
          this.queryForm.finalexecpro = ''
        }
        console.log(this.queryForm.finalexecpro == null)

        const data = {
          exammodelid: this.modelid,
          examorgid: this.queryForm.modelcode,
          finalexecpro: this.queryForm.finalexecpro,
          detail: this.tableData
        }

        const res = await SaveDeptLevel(data)
        this.$message({
          type: 'success',
          message: res.message
        })
        this.onSearch()
      } else {
        console.log('验证不通过')
      }
    },
    // 点击关闭给父组件传值
    onClose() {
      this.queryForm = {}
      this.tableData = []
      this.$emit('visiblesSP')
    },
    // 部门传回来的数据
    onChoosebm(row) {
      this.tableData[this.DataIndex].checkorgid = row.id
      this.tableData[this.DataIndex].checkorgname = row.orgname
    },
    // 岗位传回的数据
    onChoosegw(row) {
      // console.log(row)

      let id = ''
      let dutyname = ''
      row.forEach((item, index) => {
        console.log(index < 1)
        if (index < 1) {
          id += item.id
          dutyname += item.dutyname
        } else {
          id += ';' + item.id
          dutyname += ';' + item.dutyname
        }
      })
      console.log(id)
      console.log(dutyname)
      this.tableData[this.DataIndex].checkpostid = id
      this.tableData[this.DataIndex].checkpostname = dutyname
    },
    // 人员传回的数据
    onChoosery(row) {
      if (this.Namery == 'cstr') {
        console.log(row)
        let id = ''
        let ccusername = ''
        row.forEach((item, index) => {
          console.log(index < 1)
          if (index < 1) {
            id += item.id
            ccusername += item.username
          } else {
            id += ';' + item.id
            ccusername += ';' + item.username
          }
        })
        console.log(id)
        console.log(ccusername)
        this.tableData[this.DataIndex].ccuserid = id
        this.tableData[this.DataIndex].ccusername = ccusername
      } else if (this.Namery == 'spr') {
        console.log(row)
        let id = ''
        let checkusername = ''
        row.forEach((item, index) => {
          console.log(index < 1)
          if (index < 1) {
            id += item.id
            checkusername += item.username
          } else {
            id += ';' + item.id
            checkusername += ';' + item.username
          }
        })
        console.log(id)
        console.log(checkusername)
        this.tableData[this.DataIndex].checkuserid = id
        this.tableData[this.DataIndex].checkusername = checkusername
      } else if (this.Namery == 'ypzs') {
        console.log(row)
        let id = ''
        let finalusername = ''
        row.forEach((item, index) => {
          console.log(index < 1)
          if (index < 1) {
            id += item.id
            finalusername += item.username
          } else {
            id += ';' + item.id
            finalusername += ';' + item.username
          }
        })
        console.log(id)
        console.log(finalusername)
        this.tableData[this.DataIndex].finaluserid = id
        this.tableData[this.DataIndex].finalusername = finalusername
      }
    },
    // 部门删除清除id
    queryKey(index) {
      this.tableData[this.DataIndex].checkorgid = ''
      console.log(this.tableData)
    },
    // 人员删除清除id
    queryCcusername(name) {
      console.log(name)
      if (name == 'cstr') {
        this.tableData[this.DataIndex].ccuserid = ''
      } else if (name == 'spr') {
        this.tableData[this.DataIndex].checkuserid = ''
      } else if (name == 'ypzs') {
        this.tableData[this.DataIndex].finaluserid = ''
      }
    },
    // 岗位删除清除id
    queryCheckpostname() {
      this.tableData[this.DataIndex].checkpostid = ''
    }
  }
}
</script>

<style scoped>
.el-input {
  width: 173px;
}
.del {
  float: right;
}
.foot-card {
  position: sticky;
  bottom: 0px;
  /* background-color: rgb(36, 72, 113); */
  margin-left: 70px;
}
.head-card {
  z-index: 9999;
  position: sticky;
  top: 0px;
  /* background-color: rgb(36, 72, 113); */
  margin-left: 70px;
}
.foot-form {
  float: right;
}

::v-deep .examurl .el-form-item__content {
  width: 74% !important;
}
.el-row {
  display: flex;
  flex-wrap: wrap;
}
</style>
